<template>
  <view class="content"><view ref="dplayer" class="dplayer"></view></view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import HlsJs from 'hls.js';
import FlvJs from 'flv.js';
import Dplayer from 'dplayer';

const props = defineProps({
  videoUrl: {
    type: String,
    default: ''
  },
  videoType: {
    type: String,
    validator(value) {
      return ['customHls', 'customFlv'].includes(value);
    }
  }
});

const dplayer = ref();
const player = ref();
const hlsPlayer = ref();
const flvPlayer = ref();

// 初始化视频组件
function initVideo() {
  player.value = new Dplayer({
    container: dplayer.value.$el,
    live: true, // 直播模式
    autoplay: true, // 是否自动播放
    theme: '#fadfa3', // 主题色
    loop: true, // 视频是否循环播放
    lang: 'zh-cn', // 中文
    screenshot: false, // 是否开启截图
    hotkey: true, // 是否开启热键
    preload: 'auto', // 视频是否预加载
    volume: 0.7, // 默认音量
    mutex: true, // 阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
    video: {
      type: props.videoType,
      customType: {
        customHls: function(video, _player) {
          hlsPlayer.value = new HlsJs();
          hlsPlayer.value.loadSource(props.videoUrl);
          hlsPlayer.value.attachMedia(video);
        },
        customFlv: function(video, _player) {
          flvPlayer.value = FlvJs.createPlayer({
            type: 'flv',
            url: props.videoUrl
          });
          flvPlayer.value.attachMediaElement(video);
          flvPlayer.value.load();
        }
      }
    }
  });
}

onMounted(() => initVideo());

onBeforeUnmount(() => {
  if (player.value) {
    player.value.destroy();
    player.value = null;
  }
  if (hlsPlayer.value) {
    hlsPlayer.value.destroy();
    hlsPlayer.value = null;
  }
  if (flvPlayer.value) {
    flvPlayer.value.destroy();
    flvPlayer.value = null;
  }
});
</script>

<style lang="scss">
.dplayer {
  width: 300px;
  height: 300px;
}
</style>
